package com.icss.ah.test.helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

public class VelocityHelper {

	/**
     * 根据给定的vm模板和上下文生成html页面
     * @param inputVmFilePath vm模板
     * @param outputHtmlFilePath 输出html页面
     * @param context 上下文
     * @throws Exception
     */
    public static void generateHtml(String inputVmFilePath, String outputHtmlFilePath,String encoding,
        VelocityContext context) throws Exception {
        try {
            Velocity.init();
            VelocityEngine engine = new VelocityEngine();
            Template template = engine.getTemplate(inputVmFilePath, encoding);
            System.out.println("===========outputHtmlFilePath:"+outputHtmlFilePath);
            File outputFile = new File(outputHtmlFilePath); 
            System.out.println("==========outputFile:"+outputFile.exists());
//            if(!outputFile.exists()){
//            	outputFile.createNewFile();
//            }
            StringWriter writer = new StringWriter();    
            template.merge(context, writer);
            
            FileOutputStream out = new FileOutputStream(outputFile);
            out.write(writer.toString().getBytes(encoding));   
            out.close();   
        } catch (Exception ex) {
        	ex.printStackTrace();
            throw ex;
        }
    }
}
